﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SAP.WebServices;
using System.Data;
using ReadXMLFile;
using System.Collections;
using System.Globalization;
using System.Text.RegularExpressions;
namespace SAP
{
    public partial class Popup_Approval : System.Web.UI.Page
    {
        public static DataTable dtContents;
        public static DataTable dtHeader;
        private GeneralFunctions GF ;
         int RequestID = -1;
        int viewMode = 0;
        static String EmpID;
        private LoginSession CurrentLoginSession;
        static int reqStatus;
        private string GIAct = "6002001039";

        string Acc1 = "101000";
        string Acc2 = "101010";

        public static DataTable dtContentsJE;
        protected void Page_Load(object sender, EventArgs e)
        {
            SessionCheck();
            //lvContents.Items[0].Visible = false;
            this.RequestID = Request.QueryString["requestID"] == null ? -1 : Request.QueryString["requestID"] == "" ? -1 : Int32.Parse(Request.QueryString["requestID"]);
                this.viewMode = Request.QueryString["viewMode"] == null ? 0 : Request.QueryString["viewMode"] == "" ? 0 : Int32.Parse(Request.QueryString["viewMode"]);
                if (viewMode != 0)
                {
                    ib_Approve.Visible = false;
                    ib_Eject.Visible = false;
                }

            if (!IsPostBack)
            {
                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "ShowLoading", "Dialog.showLoader();", true);

                dtHeader = GF.ObjectSelect("usp_OffHeader_Select", "@hdrID", RequestID.ToString());
                if (dtHeader.Rows.Count == 0)
                    return;

                if (CurrentLoginSession.UserEmpID != dtHeader.Rows[0]["Manager_EmpID"].ToString() && viewMode==0)
                {
                    Response.Redirect("SessionErrorPage.aspx");
                }


                reqStatus = Int32.Parse(dtHeader.Rows[0]["Status"].ToString());
                if (reqStatus == 0 || reqStatus == 1) //rejected or approved
                {
                    ib_Approve.Visible = false;
                    ib_Eject.Visible = false;
                }
            
               // hf_XMLString.Value = xmlStr;
                xmlObj xmlObject = new xmlObj();

                lb_ReqNumber.Text = dtHeader.Rows[0]["hdrID"].ToString();
                EmpID = dtHeader.Rows[0]["EmpID"].ToString();

                lb_FromStore.Text = dtHeader.Rows[0]["DefaultWhsName"].ToString();
                //1. header
                //dtHeader = xmlObject.xmlStr2Ds(xmlStr).Tables[0];
                //if (!dtHeader.Columns.Contains("U_POSTxNo"))
                //    dtHeader.Columns.Add("U_POSTxNo");


                lb_RequestName.Text = dtHeader.Rows[0]["ReqName"].ToString();

                lb_ReqDate.Text = DateTime.Parse(dtHeader.Rows[0]["ReqDate"].ToString()).ToString("dd/MM/yyyy");

                lb_ReqType.Text = getRequestTypeName(dtHeader.Rows[0]["ReqType"].ToString());                             
                
                //2. detail                
                dtContents = GF.ObjectSelect("usp_OffDetail_Select", "@hdrID", RequestID.ToString());//GF.ConvertDataTable_RemoveCols(, KeepColumsContent);
                if (dtContents.Rows.Count > 0)
                    lb_ToStore.Text = dtContents.Rows[0]["WhsName"].ToString();

                this.lvContents.DataSource = dtContents;
                this.lvContents.DataBind();

                if (dtHeader.Rows[0]["ReqType"].ToString() == "E")//food transfer
                {
                    dtContentsJE = new DataTable("JDT1");
                    dtContentsJE.Columns.Add("Account");
                    dtContentsJE.Columns.Add("Debit");
                    dtContentsJE.Columns.Add("Credit");

                    MasterData md = new MasterData();

                    double totalPrice = 0;
                    foreach (DataRow detRow in dtContents.Rows)
                    {
                        String ItemCode = detRow["ItemCode"].ToString();
                        DataTable dsTr = md.GetTransValue(User.Identity.Name, ItemCode).Tables[0];

                        if (dsTr.Rows.Count > 0)
                        {
                            if (dsTr.Rows[0]["TransValue"].ToString() != "")
                                totalPrice += Double.Parse(dsTr.Rows[0]["TransValue"].ToString());
                        }
                    }
                    //totalPrice = 500;
                    if (totalPrice != 0)
                    {
                        DataRow newContentRow1 = dtContentsJE.NewRow();
                        newContentRow1["Account"] = Acc1;
                        newContentRow1["Debit"] = totalPrice;
                        newContentRow1["Credit"] = "0";
                        dtContentsJE.Rows.Add(newContentRow1);

                        DataRow newContentRow2 = dtContentsJE.NewRow();
                        newContentRow2["Account"] = Acc2;
                        newContentRow2["Debit"] = "0";
                        newContentRow2["Credit"] = totalPrice;
                        dtContentsJE.Rows.Add(newContentRow2);

                        lvSimul.DataSource = dtContentsJE;
                        lvSimul.DataBind();
                    }
                    else
                    {
                        lvSimul.DataSource = null;
                        lvSimul.DataBind();
                    }
                }
                else
                {
                    lvSimul.Visible = false;
                    lbSimulateData.Visible = false;
                }
            }
        }

        private string getRequestTypeName(string reqType) {
            string typeName = reqType=="F"?"Food Request":(reqType=="B"?"Beverage Request":(reqType=="P"?"Purchase Request":"Food Transfer"));
            return typeName;
        }

        private void _cancelAddNew()
        {
            this.lvContents.InsertItemPosition = InsertItemPosition.None;

            this.lvContents.DataBind();
        }

        private void ResetLineNo()
        {
            int i = 0;
            foreach (DataRow row in dtContents.Rows)
                row["No"] = ++i;
        }

        protected void lvContents_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                ListViewItem lvi = e.Item;
                switch (e.CommandName)
                {
                    case "CancelAddNew":
                        this._cancelAddNew();
                        this.lvContents.DataBind();
                        break;
                    case "CancelUpdate":
                        if (string.IsNullOrEmpty(((Label)lvi.FindControl("lblCode")).Text))
                        {
                            dtContents.Rows.RemoveAt(e.Item.DataItemIndex);
                            ResetLineNo();
                        }
                        this.lvContents.EditIndex = -1;
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                        //SetControlsStatus("Update");
                        break;
                    case "Update":
                        // update new data to dt
                        if (string.IsNullOrEmpty(((Label)lvi.FindControl("lblCode")).Text)) return;

                        Label lblNo = (Label)lvi.FindControl("lblNo");
                        foreach (DataRow row in dtContents.Rows)
                        {
                            if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
                            {
                                row["ItemCode"] = ((Label)lvi.FindControl("lblCode")).Text;
                                row["Dscription"] = ((Label)lvi.FindControl("lblDescription")).Text;
                                row["Quantity"] = ((TextBox)lvi.FindControl("txtQuantity")).Text;
                                break;
                            }
                        }
                        this.lvContents.EditIndex = -1;
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                        break;

                    case "DeleteItem":
                        // delete data and update dt
                        int i_idx = e.Item.DataItemIndex;

                        string detID = dtContents.Rows[i_idx]["detID"].ToString();

                        dtContents.Rows.RemoveAt(i_idx);
                        this.lvContents.EditIndex = -1;
                        ResetLineNo();

                        if (detID != "")
                        {
                            //delete from DB, in case load to update
                            ArrayList arPar = new ArrayList();
                            arPar.Add("@detID");
                            ArrayList arVal = new ArrayList();
                            arVal.Add(detID);
                            GF.ObjectUpdate("usp_OffDetail_Delete", arPar, arVal);
                            UpdateData();
                        }
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                        break;

                    default: break;
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }

        protected void lvContents_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            try
            {

                this.lvContents.EditIndex = e.NewEditIndex;

                // Reset FormatNumeric 
                string lsQty = GF.ResetFormatNumeric(dtContents.Rows[e.NewEditIndex]["Quantity"].ToString());       // Quantity

                dtContents.Rows[e.NewEditIndex]["Quantity"] = lsQty;

                this.lvContents.DataSource = dtContents;
                this.lvContents.DataBind();
                //SetControlsStatus("Edit");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }

        protected void lvContents_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            this._cancelAddNew();
        }

        protected void imgbCancel_CancelAddNew(object sender, EventArgs e)
        {
            this.lvContents.DataSource = dtContents;
            this._cancelAddNew();
        }

        protected void lvContents_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
           
            Label lblCode = (Label)lvContents.Items[e.ItemIndex].FindControl("lblCode");
            if (lblCode == null || string.IsNullOrEmpty(lblCode.Text))
            {
                e.Cancel = true;
                return;
            }
            this.lvContents.DataSource = dtContents;
            this.lvContents.DataBind();
        }

        protected void ib_Approve_Click(object sender, ImageClickEventArgs e)
        {
           
            if (dtContents.GetChanges() != null)
            {
                UpdateData();
            }
            if (dtHeader.Rows[0]["ReqType"].ToString() == "E") { //E = food transfer
                postToSAPFoodTransfer();
            }else
                postToSAP();

           
        }

        private void postToSAP() {

            DataSet ds = new DataSet("DS");
            ArrayList pra = new ArrayList();
            pra.Add("@hdrID");
            ArrayList val = new ArrayList();
            val.Add(RequestID);

            DataTable hdr = new DataTable();
            DataTable det = new DataTable();

            hdr = GF.ObjectSelect("usp_OffHeader_SAP", pra, val);
            det = GF.ObjectSelect("usp_OffDetail_SAP", pra, val);

            hdr.TableName = dtHeader.Rows[0]["TblHeaderName"].ToString();
            det.TableName = dtHeader.Rows[0]["TblLineName"].ToString();
            ds.Tables.Add(hdr.Copy());
            ds.Tables.Add(det.Copy());
            DocumentXML objInfo = new DocumentXML();


            String xml = objInfo.ToXMLStringFromDSForSAP(dtHeader.Rows[0]["DocType"].ToString(), ds);

            if (dtHeader.Rows[0]["ReqType"].ToString() == "P")
            {
                xml = Regex.Replace(xml, "<DocType>.*</DocType>", String.Empty);
                xml = Regex.Replace(xml, "<ObjType>.*</ObjType>", String.Empty);
            }
            SAP.WebServices.Transaction ts = new WebServices.Transaction();

            DataSet dsResult = ts.CreateMarketingDocument(xml, User.Identity.Name, dtHeader.Rows[0]["DocType"].ToString(), "", false);
            //WriteXMLLog(DocType, requestXML, ds.Tables[0].Rows[0]["ErrMsg"].ToString());

            if ((int)dsResult.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                SaveMessage(RequestID, xml, dsResult.Tables[0].Rows[0]["ErrMsg"].ToString());
                Session["errorMessage"] = dsResult.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = xml;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                    "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(dsResult.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                lb_Message.Text = "Error in approval: " + dsResult.Tables[0].Rows[0]["ErrMsg"];
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                              "Dialog.hideLoader();", true);
            }
            else
            {  //successfully send to SAP
                SaveMessage(RequestID, xml, dsResult.Tables[0].Rows[0]["ErrMsg"].ToString());
                ArrayList param1 = new ArrayList();
                param1.Add("@hdrID");
                ArrayList vals1 = new ArrayList();
                vals1.Add(RequestID);
                GF.ObjectUpdate("usp_OffHeader_Approve", param1, vals1);
                lb_Message.Text = "Approved!";

                GetDefault df = new GetDefault();
                DataTable dtUserEmail = df.GetLoginInfo(dtHeader.Rows[0]["U_UserID"].ToString(), 0).Tables[0];
                if (dtUserEmail.Rows[0]["EmployeeEmail"].ToString() != "")
                {
                    Emailling omail = new Emailling();
                    omail.SendMailNow(dtUserEmail.Rows[0]["EmployeeEmail"].ToString(), "Your request have just been approved.", omail.GetTemplate_Approve(RequestID));
                }
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "OKPopup", "Main.okDialogClick('ApproveCallBack');", true);
          
                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "ShowLoading", "Dialog.showLoader();", true);

                //ClearScreen();
            }
           
        }

        private void postToSAPFoodTransfer() {

            GetDefault df = new GetDefault();
            DataTable dtUserEmail = df.GetLoginInfo(dtHeader.Rows[0]["U_UserID"].ToString(), 0).Tables[0];
           
            //1. PUSH XML TO SAP
            
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "ShowLoader", "Dialog.showLoader();", true);

            if (dtHeader.Rows.Count == 0)
                return;

            DataTable dtHeaderJE = new DataTable("OJDT");
            dtHeaderJE.Columns.Add("RefDate");
            dtHeaderJE.Columns.Add("DueDate");
            dtHeaderJE.Columns.Add("TaxDate");
            dtHeaderJE.Columns.Add("Memo");
            dtHeaderJE.Columns.Add("Ref1");
            dtHeaderJE.Columns.Add("Ref2");
            dtHeaderJE.Columns.Add("Ref3");
            dtHeaderJE.Columns.Add("U_UserID");
            dtHeaderJE.Rows.Add();

            DataRow drJE = dtHeaderJE.Rows[0];
            string dateFmt = DateTime.Parse(dtHeader.Rows[0]["DocDate"].ToString()).ToString("yyyMMdd");
            drJE["RefDate"] = dateFmt;
            drJE["DueDate"] = dateFmt;
            drJE["TaxDate"] = dateFmt;
            drJE["Memo"] = "Remark";
            drJE["Ref1"] = "REF 1";
            drJE["Ref2"] = "Ref 2";
            drJE["Ref3"] = "Ref 3";
            drJE["U_UserID"] = User.Identity.Name;

            ArrayList param = new ArrayList();
            param.Add("@hdrID");
            ArrayList vals = new ArrayList();
            vals.Add(RequestID);


            if (dtContentsJE.Rows.Count == 0)
            {
                GF.ObjectUpdate("usp_OffHeader_Approve", param, vals);
                SaveMessage(RequestID, "", "Account values equal 0");
                if (dtUserEmail.Rows[0]["EmployeeEmail"].ToString() != "")
                {
                    Emailling omail = new Emailling();
                    omail.SendMailNow(dtUserEmail.Rows[0]["EmployeeEmail"].ToString(), "Your food transfer have just been approved.", omail.GetTemplate_Approve(RequestID));
                }

                ScriptManager.RegisterStartupScript(this, this.GetType(), "OKPopup", "Main.okDialogClick('ApproveCallBack');", true);
            }
            else { 
                

                DocumentXML objInfo = new DocumentXML();
                DataSet dsJE = new DataSet("DS");
                Array arrContentsCols = new string[] { "Debit", "Credit" };

                dsJE.Tables.Add(dtHeaderJE.Copy());
                dsJE.Tables.Add(GF.ResetFormatNumeric(dtContentsJE.Copy(), arrContentsCols));

                String xmlStrJE = objInfo.ToXMLStringFromDS("30", dsJE);
                SAP.WebServices.Transaction ts = new WebServices.Transaction();

                DataSet dsResult = ts.CreateMarketingDocument(xmlStrJE, User.Identity.Name, "30", "", false);
                if ((int)dsResult.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    SaveMessage(RequestID, xmlStrJE, dsResult.Tables[0].Rows[0]["ErrMsg"].ToString());
                    Session["errorMessage"] = dsResult.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = xmlStrJE;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(dsResult.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    //2. If ok: update XML_Off status to 1
                   
                    GF.ObjectUpdate("usp_OffHeader_Approve", param, vals);
                    SaveMessage(RequestID, xmlStrJE, dsResult.Tables[0].Rows[0]["ErrMsg"].ToString());
                    if (dtUserEmail.Rows[0]["EmployeeEmail"].ToString() != "")
                    {
                        Emailling omail = new Emailling();
                        omail.SendMailNow(dtUserEmail.Rows[0]["EmployeeEmail"].ToString(), "Your food transfer have just been approved.", omail.GetTemplate_Approve(RequestID));
                    }

                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "OKPopup", "Main.okDialogClick('ApproveCallBack');", true);
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                  "Dialog.hideLoader();", true);

            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                        "Dialog.hideLoader();", true);
        }

        private void SaveMessage(int hdrID, string XMLString, string ErrorMsg) {
            ArrayList param = new ArrayList();
            param.Add("@hdrID");
            param.Add("@XMLString");
            param.Add("@ErrMsg");
            ArrayList vals = new ArrayList();
            vals.Add(hdrID);
            vals.Add(XMLString);
            vals.Add(ErrorMsg);
            GF.ObjectUpdate("usp_OffHeader_Message", param, vals);

        }

        protected void ib_Eject_Click(object sender, ImageClickEventArgs e)
        {
            ArrayList param = new ArrayList();
            param.Add("@hdrID");
            ArrayList vals = new ArrayList();
            vals.Add(RequestID);
            GF.ObjectUpdate("usp_OffHeader_Eject", param, vals);
            lb_Message.Text = "Rejected!";

            GetDefault df = new GetDefault();
            DataTable dtUserEmail = df.GetLoginInfo(dtHeader.Rows[0]["U_UserID"].ToString(), 0).Tables[0];
            if (dtUserEmail.Rows[0]["EmployeeEmail"].ToString() != "")
            {
                Emailling omail = new Emailling();
                omail.SendMailNow(dtUserEmail.Rows[0]["EmployeeEmail"].ToString(), "Your request have just been rejected.", omail.GetTemplate_Reject(RequestID));
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                     "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);

            ScriptManager.RegisterStartupScript(this, this.GetType(), "OKPopup", "Main.okDialogClick('RejectCallBack');", true);
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                "Dialog.hideLoader();", true);   
            //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "ShowLoading", "Dialog.showLoader();", true);

        }
        
        

        protected void UpdateData()
        {
            try
            {
                ArrayList arrPar = new ArrayList();
                arrPar.Add("@detID");
                arrPar.Add("@No");
                arrPar.Add("@Quantity");
                arrPar.Add("@WhsCode");
                arrPar.Add("@LineNum");
                arrPar.Add("@WhsName");
                ArrayList arrVal = new ArrayList();
                foreach (DataRow dr in dtContents.Rows)
                {
                    if (dr.RowState == DataRowState.Modified)
                    {
                        arrVal.Clear();
                        arrVal.Add(dr["detID"]);
                        arrVal.Add(dr["No"]);
                        arrVal.Add(dr["Quantity"]);
                        arrVal.Add(dr["WhsCode"]);
                        arrVal.Add(dr["LineNum"]);
                        arrVal.Add(dr["WhsName"]);
                        GF.ObjectUpdate("usp_OffDetail_Update", arrPar, arrVal);
                    }
                }
                dtContents.AcceptChanges();
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                       "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                 "Dialog.hideLoader();", true);

            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }
        public void SessionCheck()
        {

            if (Session["LoginSession"] != null)
            {
                this.CurrentLoginSession = (LoginSession)Session["LoginSession"];
                GF = new GeneralFunctions(CurrentLoginSession.UserName);
            }
            else
            {
                Response.Redirect("SessionErrorPage.aspx");
            }

        }    
    }
}